package app.service.goods;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import app.model.goods.GoodsBase;
import app.model.goods.GoodsStock;
import app.util.StringUtil;
import base.PageInfo;
import base.category.sys.YesOrNo;
import base.dao.HibernateDao;
import base.service.BaseService;

@Service
public class GoodsBaseService extends BaseService {

	@Autowired
	private HibernateDao<GoodsBase> hibernateDao;
	
	@Override
	public HibernateDao<GoodsBase> getDao() {
		return this.hibernateDao;
	}
	
	/**
	 * 查询商品
	 * @param pageInfo
	 * @param goodsName 
	 * @return
	 */
	public PageInfo queryGoodsBasePage(PageInfo pageInfo, String goodsName) {
		String sql = "select * from goods_base a where a.is_use = "+YesOrNo.YES_INT;
		if(StringUtil.isNotEmpty(goodsName)){
			sql += " and a.goods_name like '%"+goodsName+"%'";
		}
		sql += " order by a.create_time desc";
		PageInfo page = getDao().queryPageListBySql(pageInfo, sql);
		return page;
	}

	public void saveEntity(GoodsBase goodsBase) {
		getDao().save(goodsBase);
		
//		//保存关系
//		GoodsUserRel goodsUserRel = new GoodsUserRel();
//		goodsUserRel.setGoodsId(goodsBase.getId());
//		goodsUserRel.setGoodsName(goodsBase.getGoodsName());
//		LoginUser loginUser = LoginUserUtil.getLoginUser();
//		goodsUserRel.setUserId(loginUser.getId());
//		goodsUserRel.setUserName(loginUser.getUserName());
//		getDao().save(goodsUserRel);
		//库存
		GoodsStock goodsStock = new GoodsStock();
		goodsStock.setGoodsId(goodsBase.getId());
		goodsStock.setGoodsStock(0.0);
		getDao().save(goodsStock);
	}

	public void updateEntity(GoodsBase goodsBase) {
		getDao().mergeAndUpdate(goodsBase);
	}

	public GoodsBase queryEntityById(String id) {
		String sql = "select * from goods_base a where a.id = '"+id+"'";
		Object entity = getDao().queryEntityBySql(sql , GoodsBase.class);
		return (GoodsBase)entity;
	}

	public void delEntity(String ids) {
		if(!StringUtils.isEmpty(ids)){
			String[] idsArray = ids.split(",");
			for (int i = 0; i < idsArray.length; i++) {
				GoodsBase gb = new GoodsBase();
				gb.setId(idsArray[i]);
				getDao().del(gb);
			}
		}
	}
}
